package com.example.demo.service.impl;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.commons.exception.ServiceException;
import com.example.demo.commons.r.Codes;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao , User> implements UserService {
    @Override
    public boolean save(User entity) {
        // 密码加密
        //MD5 -> Hash算法（文明 -> MD5 -> 32字符串形式）
        // password=123456

        // 验证用户名是否已经存在
        User user = this.query().eq("username",entity.getUsername()).one();
        if(user != null){
               // 用户已存在
            throw new ServiceException(Codes.USER_EXISTS);
        }

        entity.setPassword(MD5.create().digestHex(entity.getPassword()));
        //password = 32字符串形式

        //昵称加密
        String pinyin = PinyinUtil.getPinyin(entity.getNickname()).replace(" "," ");
        entity.setPinyin(pinyin);

        // entity -> 1.password 2.多了一个pinyin
        return  super.save(entity);

    }

    @Override
    public User queryUserName(String username) {
        User user = this.query().eq("username",username).one();

        return user;
    }


    @Override
    public boolean saveBatch(Collection<User> entityList) {
        return super.saveBatch(entityList);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<User> entityList) {
        return super.saveOrUpdateBatch(entityList);
    }

    @Override
    public boolean saveOrUpdate(User entity, Wrapper<User> updateWrapper) {
        return super.saveOrUpdate(entity, updateWrapper);
    }
}
